import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:flutter_app1/pages/search_page.dart';
import 'package:flutter_app1/pages/speak_page.dart';
import 'package:flutter_app1/dao/home_dao.dart';
import 'package:flutter_app1/model/common_model.dart';
import 'package:flutter_app1/model/grid_nav_model.dart';
import 'package:flutter_app1/model/home_model.dart';
import 'package:flutter_app1/model/sales_box_model.dart';
import 'package:flutter_app1/widget/search_bar.dart';
import 'package:flutter_app1/widget/loading_container.dart';
import 'package:flutter_app1/widget/webview.dart';
import 'package:flutter_app1/widget/local_nav.dart';
import 'package:flutter_app1/widget/grid_nav_new.dart';
import 'package:flutter_app1/widget/sales_box.dart';
import 'package:flutter_app1/widget/sub_nav.dart';
import 'package:flutter_app1/plugin/square_swiper_pagination.dart';
import 'package:flutter_app1/util/navigator_util.dart';

const APPBAR_SCROLL_OFFSET = 100;
const SEARCH_BAR_DEFAULT_TEXT = '目的地 | 酒店 | 景点 | 航班号';

/// 首页
class HomePage extends StatefulWidget {
  const HomePage({super.key, required this.title});
  final String title;
  
  @override
  State<HomePage> createState() => _HomePageState();
}

/// 一个有状态组件
/// 下划线_代表这个类、方法或成员变量是私有的，在类的外部无法访问
class _HomePageState extends State<HomePage> {
  List<CommonModel> localNavList = []; // 本地导航列表
  late GridNavModel gridNavModel; // 首页网格卡片模型
  double appBarAlpha = 0;
  List<CommonModel> subNavList = []; // 子导航列表
  SalesBoxModel? salesBoxModel; // 活动入口模型
  bool _isLoading = true;
  List<CommonModel> bannerList = []; // 轮播图

  @override
  void initState() {
    super.initState();
    // 刷新句柄
    _handleRefresh();
    // 设置应用程序的系统 UI 覆盖层样式为浅色模式。
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
  }

  /// 每次调用setState时都会重新运行此方法flutter框架已经过优化，以加快重新运行构建方法,
  /// 这样，您就可以重建任何需要更新的东西，而不必单独更改小部件的实例。
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xfffafafc),
        body: LoadingContainer(
            isLoading: _isLoading,
            child: Stack(children: <Widget>[
              /// 移除当前 MediaQuery 数据中的内边距（padding）信息
              MediaQuery.removePadding(
                removeTop: true,
                context: context,
                /// 创建一个用于侦听通知
                child: NotificationListener(
                  onNotification: (scrollNotification) {
                    if (scrollNotification is ScrollUpdateNotification && // 组件是否已更新
                        scrollNotification.depth == 0) {
                      // 只监听子组件，不监听孙组件
                      _onScroll(scrollNotification.metrics.pixels);
                    }
                    return true;
                  },
                  /// 创建刷新指示器
                  child: RefreshIndicator(
                    onRefresh: _handleRefresh,
                    child: ListView(
                      children: <Widget>[
                        Container(
                          height: 262,
                          child: Stack(
                            /// Stack 组件能让其子组件堆叠显示，它通常和 Positioned 组件配合使用，布局结构代码如下：
                            children: <Widget>[
                              Container(
                                height: 210,
                                /// 轮播图
                                child: Swiper(
                                  itemCount: bannerList.length, // 滚动图片的数量
                                  autoplay: true, // 自动播放
                                  pagination: SwiperPagination(
                                    // 指示器
                                    /// 方形轮播图分页
                                    builder: SquareSwiperPagination(
                                      size: 6, // 指示器的大小
                                      activeSize: 6, // 激活状态指示器的大小
                                      color: Colors.white.withAlpha(80), // 颜色
                                      activeColor: Colors.white, // 激活状态的颜色
                                    ),
                                    alignment: Alignment.bottomRight, // 底部右对齐
                                    margin:
                                        EdgeInsets.fromLTRB(0, 0, 14, 28), // 边距
                                  ),
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    // 构造器
                                    return GestureDetector(
                                      onTap: () {
                                        CommonModel model = bannerList[index];
                                        Navigator.push(
                                          context,
                                          // 一种模式路线，用平台自适应转换替换整个屏幕
                                          MaterialPageRoute(
                                            builder: (context) => WebView(
                                              url: model.url,
                                            ),
                                          ),
                                        );
                                      },
                                      child: Image.network(
                                        bannerList[index].icon,
                                        fit: BoxFit.fill, // 通过扭曲源的纵横比来填充目标框
                                      ),
                                    );
                                  },
                                ),
                              ),
                              Positioned(
                                /// 这个就是icon导航，通过 Positioned 固定显示位置
                                top: 188,
                                child: Container(
                                  width: MediaQuery.of(context).size.width,
                                  padding: EdgeInsets.fromLTRB(14, 0, 14, 0),
                                  child: LocalNav(
                                    localNavList: localNavList,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          /// 这里放的网格导航及其他
                          padding: EdgeInsets.fromLTRB(14, 0, 14, 0),
                          margin: EdgeInsets.only(top: 10),
                          child: Column(
                            children: <Widget>[
                              /// 网格导航
                              GridNavNew(),
                              Padding(
                                padding: EdgeInsets.only(top: 10),
                              ),
                              SubNav(// 次级导航
                                subNavList: subNavList,
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 10),
                              ),
                              SalesBox(// 活动入口模型
                                salesBoxModel: salesBoxModel,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              _appBar,
            ])));
  }

  Widget get _appBar {
    return Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              /// AppBar渐变遮罩背景
              colors: [Color(0x66000000), Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Container(
            padding: EdgeInsets.fromLTRB(14, 20, 0, 0),
            height: 86.0,
            decoration: BoxDecoration(
                color:
                Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255),
                boxShadow: [
                  BoxShadow(
                    color: appBarAlpha == 1.0
                        ? Colors.black12
                        : Colors.transparent,
                    offset: Offset(2, 3),
                    blurRadius: 6,
                    spreadRadius: 0.6,
                  ),
                ]),
            child: SearchBarWidget(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,/// 点击回调函数
              defaultText: SEARCH_BAR_DEFAULT_TEXT,/// 提示文字
              leftButtonClick: () {}, /// 左边边按钮点击回调函数
              speakClick: _jumpToSpeak,/// 点击话筒回调函数
              rightButtonClick: _jumpToUser,/// 右边边按钮点击回调函数
            ),
          ),
        ),
        Container(
            height: appBarAlpha > 0.2 ? 0.5 : 0,
            decoration: BoxDecoration(
                boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]))
      ],
    );
  }

  /// 刷新句柄
  Future<Null> _handleRefresh() async {
    try {
      debugPrint("刷新句柄");
      HomeModel homeModel = await HomeDao.fetch();
      debugPrint("homeModel ${homeModel.toString()}");
      setState(() {
        localNavList = homeModel.localNavList;
        gridNavModel = homeModel.gridNav;
        subNavList = homeModel.subNavList;
        salesBoxModel = homeModel.salesBox;
        bannerList = homeModel.bannerList;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        debugPrint(e.toString());
        setState(() {
          _isLoading = false;
        });
      });
    }
    return null;
  }

  /// 滚动
  void _onScroll(offset) {
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    }
    setState(() {
      appBarAlpha = alpha;
    });
    print(alpha);
  }

  /// 右边边按钮点击回调函数
  void _jumpToUser() {
    NavigatorUtil.push(
        context,
        WebView(
          url:
          'https://m.ctrip.com/webapp/servicechatv2/messagelist/?from=%2Fwebapp%2Fmyctrip%2Findex',
          hideHead: false,
          hideAppBar: false,
          title: '我的消息',
        ),
        callBack: () {
          SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
        }
    );
  }

  /// 点击话筒回调函数
  _jumpToSpeak() {
    NavigatorUtil.push(context, SpeakPage());
  }

  /// 点击回调函数
  void _jumpToSearch() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SearchPage(
          hint: SEARCH_BAR_DEFAULT_TEXT,
          hideLeft: false,
        ),
      ),
    );
  }
}
